import { ref, computed, watch } from 'vue'
import { defineStore } from 'pinia'
import { getList} from '../data/index'
import type { Title,List } from '../data/index'
import router from '../router/index'

export const useFoodStore = defineStore('food', () => {
  const title = ref<Title[]>( JSON.parse(localStorage.getItem('title') || '') ||[])
  const compareList = ref<List[]>( JSON.parse(localStorage.getItem('compareList') || '') ||[])

  const getFoods = async () => {
    const res = await getList()
    title.value = res.data.value;

  }

  const addFood = (food: string) => {
    title.value.forEach((item) => {
      item.list.forEach((it) => {
        if (it.name === food) {
          it.isChecked =!it.isChecked
          if(it.isChecked){
            compareList.value.push(it)
          }else{
            compareList.value = compareList.value.filter((i)=>{
              return i.name!== food
            })
          }
        }
      })
    })

    
    



  }

  watch([title,compareList],()=>{
    localStorage.setItem('title',JSON.stringify(title.value))
    localStorage.setItem('compareList',JSON.stringify(compareList.value))
    },{
      deep:true
  })

  // JSON.parse(localStorage.getItem('title') || '') ||
  // JSON.parse(localStorage.getItem('compareList') || '') ||
  // const goDetail = () => {
  //   router.push({
  //     path:'/detail',
  //     query:{
  //       list:JSON.stringify(compareList.value)
  //     }
  //   })
  // }


  return { 
    title,
    getFoods,
    addFood,
    compareList,
    // goDetail
   }
})
